<?php

namespace Hilaoyu\LaravelPrivateApi;

use Closure;
use Hilaoyu\Utils\UtilAes;
use Hilaoyu\Utils\UtilStr;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;


abstract class PrivateApiDeDataMiddlewareAbstract
{
    abstract protected function getEncryptSecret(Request $request):string;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {

        //解密数据
        try{
            $encryptor = UtilAes::make($this->getEncryptSecret($request));
            $en_data = $request->input('data','');
            //dd($en_data,$request->input());
            $request->offsetUnset('data');
            $data = $encryptor->decrypt($en_data);

            if(!$data){
                return comResponse()->failed('数据解密错误')->json();
            }

            //数据是否过期
            $expiration_time_minutes = 3;
            if(!config('app.debug')){
                $timestamp = data_get($data,'_timestamp',data_get($data,'timestamp',0));
                //dd(intval($timestamp) , Carbon::now()->utc()->subMinutes(5)->timestamp);
                $time_min = Carbon::now()->utc()->subMinutes($expiration_time_minutes)->unix();
                $time_max = Carbon::now()->utc()->addMinutes($expiration_time_minutes)->unix();
                if($timestamp <= $time_min || $timestamp > $time_max){
                    //todo 调试暂时禁用，正式时开启

                    return comResponse()->failed('数据已过期')->json();
                }
                //数据是否已处理过
                $data_id = data_get($data,'_data_id','');

                if(!$data_id){
                    return comResponse()->failed('数据标识错误')->json();
                }
                $data_id_cache_key = 'PrivateApiDeDataProcessedId:'.$data_id;
                if(Cache::get($data_id_cache_key)){
                    return comResponse()->failed('数据已处理过了')->json();
                }

                Cache::remember($data_id_cache_key,Carbon::now()->addMinutes($expiration_time_minutes),function (){
                    return true;
                });

            }


            //把解密后的数据设置到请求中，以供后续使用
            unset($data['timestamp']);
            unset($data['_data_id']);
            $request->route()->setParameter('_encryptor',$encryptor);
            $request->route()->setParameter('_data',$data);
            $replace = [];
            if(data_get($data,'pager_offset','')){
                $replace['pager_offset'] = data_get($data,'pager_offset','');
            }
            if(data_get($data,'pager_start','')){
                $replace['pager_start'] = data_get($data,'pager_start','');
            }
            if(data_get($data,'pager_page','')){
                $replace['pager_page'] = data_get($data,'pager_page','');
            }
            if(!empty($replace)){
                $request->replace($replace);
            }



        }catch (\Exception $exception){

            return comResponse()
                ->failed('系统错误')
                ->withErrors(UtilStr::toUtf8($exception->getMessage()))
                ->json();
        }

        return $next($request);
    }
}
